package com.lmk.ms.common.dto.validate;

import com.lmk.ms.common.utils.MsReflectionUtils;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.ArrayList;
import java.util.List;

/**
 * 校验异常结构体
 *
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2021/08/05
 */
@Data
@NoArgsConstructor
@Accessors(chain = true)
@Schema(description = "参数校验错误")
public class ValidateError {

    @Schema(description = "错误码")
    String code;

    @Schema(description = "错误提示")
    String msg;

    @Schema(description = "错误字段")
    String field;

    @Schema(description = "错误字段名称")
    String fieldName;

    @Schema(description = "错误字段值")
    Object fieldValue;

    /**
     * 将自动校验异常转为 ValidateError
     *
     * @param result
     * @return
     * @author lvshengchao
     * @since 2021年1月7日
     */
    public static List<ValidateError> convert(BindingResult result) {
        List<ValidateError> list = new ArrayList<>();
        if (result == null) {
            return list;
        }

        List<ObjectError> allErrors = result.getAllErrors();
        for (ObjectError error : allErrors) {
            ValidateError ve = new ValidateError();
            ve.setCode(error.getCode());
            ve.setMsg(error.getDefaultMessage());

            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                String propertyName = MsReflectionUtils.getApiModelProperty(result.getTarget().getClass(), fieldError.getField());

                ve.setField(fieldError.getField());
                ve.setFieldName(propertyName);
                ve.setFieldValue(fieldError.getRejectedValue());
            }

            list.add(ve);
        }

        return list;
    }

}
